﻿using System;
using System.Collections;
using System.Diagnostics;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Context;
using NHibernate.Event;
using NHibernate.SqlCommand;
using NHibernate.Tool.hbm2ddl;

using Subfaculty.Infrastructure.Repositories.Mapping;
using Subfaculty.Common.Interfaces;

namespace Subfaculty.WebApplication
{
	public class SessionProvider : ISessionProvider
	{
		#region Fields
		private ISessionFactory _sessionFactory;
		#endregion

		#region Properties
		public ISession Session
		{
			get
			{
				var session = _sessionFactory.GetCurrentSession();
				return session;
			}
		}

		public ISessionFactory SessionFactory
		{
			get { return _sessionFactory; }
		}
		#endregion

		#region Methods
		public SessionProvider()
		{
			var dbConfiguration = MsSqlConfiguration.MsSql2008.ShowSql().ConnectionString(c => c.FromConnectionStringWithKey("ApplicationServices"));

			var configuration = Fluently
				.Configure(new Configuration().SetInterceptor(new LoggingInterceptor()))
				.Database(dbConfiguration.ShowSql())
				.Mappings(m => m.FluentMappings.AddFromAssemblyOf<DisciplineMapping>())
				.ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web"));
				

			configuration.ExposeConfiguration(cfg =>
			{
				new SchemaUpdate(cfg).Execute(false, true);
			});

			_sessionFactory = configuration.BuildSessionFactory();
		}

		public void OpenSessionForContext()
		{
			var session = _sessionFactory.OpenSession();
			CurrentSessionContext.Bind(session);
		}

		public void CloseCurrentContextSession()
		{
			if (Session != null)
			{
				Session.Close();
				CurrentSessionContext.Unbind(_sessionFactory).Dispose();
			}
		}
		#endregion
	}
	public class LoggingInterceptor : EmptyInterceptor
	{
		public override SqlString OnPrepareStatement(SqlString sql)
		{
			Trace.WriteLine(sql);
			return sql;
		}
	}
}